from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from meiduo_admin.serializers.orders import OrderInfoSerializer
from meiduo_admin.utils import PageNum
from orders.models import OrderInfo

class OrderInfoView(ModelViewSet):
    queryset = OrderInfo.objects.all()
    serializer_class = OrderInfoSerializer
    pagination_class = PageNum
    permission_classes = [IsAdminUser]


        # 父类获取查询集数据方法不符合需求

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword is None or keyword == '':
            return OrderInfo.objects.all()
        else:
            return OrderInfo.objects.filter(order_id__contains=keyword)

    # 修改订单状态
    @action(methods=['put'],detail=True)
    def status(self,request,pk):
        # 1.根据order_id查询订单状态
        try:
            order=OrderInfo.objects.get(order_id=pk)
        except:
            return Response({'error':'订单不存在'},status=400)
        # 2.修改订单状态
        status=request.data.get('status')
        order.status=status
        order.save()
        # 3.返回结果
        return Response({
            'order_id':pk,
            'status':status,
        })